package cn.edu.njnu.opengmpback.collaboration.service.Impl;
import cn.edu.njnu.opengmpback.common.utils.JsonResult;
import cn.edu.njnu.opengmpback.common.utils.ResultUtils;
import cn.edu.njnu.opengmpback.collaboration.entity.CollabProject;
import cn.edu.njnu.opengmpback.collaboration.repository.CollabProjectRepository;
import cn.edu.njnu.opengmpback.collaboration.service.CollabProjectService;
import cn.edu.njnu.opengmpback.collaboration.enums.ActivityType;
import cn.edu.njnu.opengmpback.collaboration.entity.UserEntity;
import cn.edu.njnu.opengmpback.collaboration.repository.UserRepository;
import cn.edu.njnu.opengmpback.collaboration.dao.Folder.FolderDaoImpl;


import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class CollabProjectsServiceImpl implements CollabProjectService{
    
    

    private final CollabProjectRepository collabProjectRepository;
    private final UserRepository userRepository;
    private final FolderDaoImpl folderDao;

    public CollabProjectsServiceImpl(CollabProjectRepository collabProjectRepository, UserRepository userRepository, FolderDaoImpl folderDao) {
        this.collabProjectRepository = collabProjectRepository;
        this.userRepository = userRepository;
        this.folderDao = folderDao;
    }

    @Override
    public JsonResult inquiryByConditions(String category, String tag, String keyword, String userId, int page, int size) {
        try {
            System.out.println("🔍 接收到的参数 - tag: " + tag + ", category: " + category);
            Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
            Pageable pageable = PageRequest.of(page - 1, size, sort);

            Page<CollabProject> projects = null;
            if (keyword.equals("")) {
                if (userId.equals("")) {
                    if (tag.equals("All")) {
                        projects = collabProjectRepository.findCollabProjectsByPrivacyIsNot("Private", pageable);
                    } else {
                        // if (tag.equals("")) {
                        //     projects = collabProjectRepository.findCollabProjectsByPrivacyIsNotAndCategoryEquals("Private", category, pageable);
                        // }
                        //  else {
                            projects = collabProjectRepository.findCollabProjectsByPrivacyIsNotAndCategoryEqualsAndTagContaining("Private", category, tag, pageable);
                        // }
                    }
                } else {
                    if (category.equals("All")) {
                        projects = collabProjectRepository.findCollabProjectsByPrivacyIsAndCreatorIsOrPrivacyIsNot("Private", userId, "Private", pageable);
                    } else {
                        if (tag.equals("")) {
                            projects = collabProjectRepository.findCollabProjectsByPrivacyIsAndCreatorIsOrPrivacyIsNotAndCategoryEquals("Private", userId, "Private", category, pageable);
                        } else {
                            projects = collabProjectRepository.findCollabProjectsByPrivacyIsAndCreatorIsOrPrivacyIsNotAndCategoryEqualsAndTagContaining("Private", userId, "Private", category, tag, pageable);
                        }
                    }
                }
            } else {
                if (userId.equals("")) {
                    projects = collabProjectRepository.findCollabProjectsByNameLikeOrDescriptionLikeAndPrivacyIsNot(keyword, keyword, "Private", pageable);
                } else {
                    projects = collabProjectRepository.findCollabProjectsByNameLikeOrDescriptionLikeAndPrivacyIsAndCreatorIsOrPrivacyIsNot(keyword, keyword, "Private", userId, "Private", pageable);
                }
            }

            JSONObject result = new JSONObject();
            result.put("totalPage", projects.getTotalPages());
            result.put("count", projects.getTotalElements());
            result.put("projectList", projects.getContent());

            if (projects.isEmpty())
                return ResultUtils.error(-1, "None");
            else
                return ResultUtils.success(result);

        } catch (Exception ex) {
            return ResultUtils.error(-2, ex.toString());
        }
    }


    @Override
    public JsonResult createCollabProject(CollabProject collabProject) {
        try {
            /**
             * Save project info
             */
            // Created time and active time
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            collabProject.setCreatedTime(dateFormat.format(date));
            collabProject.setActiveTime(dateFormat.format(date));

            // Aid
            String collabProjectId = UUID.randomUUID().toString();
            collabProject.setAid(collabProjectId);

            // Set project member
            String creatorId = collabProject.getCreator();
            JSONArray members = new JSONArray();
            JSONObject creator = new JSONObject();

            creator.put("userId", creatorId);
            creator.put("role", "manager");
            members.add(creator);

            collabProject.setMembers(members);

            // set type
            collabProject.setType(collabProject.getType());
            if (collabProject.getType().equals(ActivityType.Activity_Group)) {
                collabProject.setChildren(new ArrayList<>());
            }

            // children
            ArrayList<String> children = new ArrayList<>();
            collabProject.setChildren(children);

            /**
             * Update user info
             */
            // Update user information
            UserEntity user = findByUserId(creator.getString("userId"));
            if (user == null) return ResultUtils.error(-1, "Fail: user does not exist");

            ArrayList<String> createdProjects = user.getCreatedProjects();
            if (createdProjects == null) {
                createdProjects = new ArrayList<>();
            }
            createdProjects.add(collabProjectId);
            user.setCreatedProjects(createdProjects);
            /**
             * Resource folder
             */
            folderDao.createFolder(collabProject.getName(), "", collabProjectId);

            collabProjectRepository.save(collabProject);
            userRepository.save(user);
            //Spring Data 自动提供的 CRUD 方法（save, delete, findById 等）
            // Service.save() → Repository.save() → SimpleMongoRepository.save() → MongoTemplate → MongoDB>


            return ResultUtils.success(collabProject);
        } catch (Exception ex) {
            return ResultUtils.error(-2, ex.toString());
        }
    }


    private UserEntity findByUserId(String userId) {
        Optional optional = userRepository.findById(userId);
        if (optional.isPresent()) {
            Object user = optional.get();
            return (UserEntity) user;
        } else {
            return new UserEntity();
        }
    }


}


